<?php

namespace app\common\model\banxi\subject;

use app\common\enums\SubjectKnowledgeStatusEnum;
use app\common\enums\SubjectQuestionStatusEnum;
use app\common\enums\SubjectTeachChapterStatusEnum;
use app\common\model\banxi\subject\SubjectKnowledge as SubjectKnowledgeModel;
use app\common\model\common\BaseModel;
use think\exception\ValidateException;
use think\Model;
use think\model\concern\SoftDelete;

/**
 * Attachment模型
 * @property string url              文件物理路径
 * @property int quote            上传(引用)次数
 * @property int last_upload_time 最后上传时间
 */
class SubjectTeachChapter extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_subject_teach_chapter';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'statusCn'
    ];
    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'subjectTeachId' => 'string',
        'subjectKnowledgeId' => 'string',
        'sortNum' => 'string',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];

    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------
    public function getStatusCnAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        return (new SubjectTeachChapterStatusEnum())->getDescription($value) ?? '';
    }

    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //-----------------------------------------------------------------------------------

    public function saveOrUpdate($data)
    {
        if (empty($data['attachment'])) {
            $data['attachment'] = [];
        }
        $data['attachment'] = json_encode($data['attachment']);
        $id = $data['id'] ?? null;
        if ($id == null) {
            $gradeModel = new self();
            $gradeModel->save($data);
        } else {
            $gradeModel = self::where('id', $id)->find();
            if (empty($gradeModel)) {
                throw new ValidateException('章节不存在');
            }
            $gradeModel->save($data);
        }
        return true;
    }

    /**
     * 设置题库
     * @param $teachChapterId
     * @param $questionType
     * @param $question
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setQuestion($teachChapterId, $questionType, $question): bool
    {
        $info = self::where('id', $teachChapterId)->find();
        if (empty($info)) {
            throw new ValidateException('章节不存在');
        }
        $questions = explode(',', $question);
        $questions = SubjectQuestion::where([
            ['id', 'in', $questions],
            ['status', '=', SubjectQuestionStatusEnum::E1]
        ])->column('id');
        if (empty($questions)) {
            throw new ValidateException('没有可用的题库');
        }
        $question = implode(',', $questions);
        if ($questionType == 1) {
            $info->beforeClassQuestion = $question;
        }
        if ($questionType == 2) {
            $info->inClassQuestion = $question;
        }
        if ($questionType == 3) {
            $info->afterClassQuestion = $question;
        }
        $info->save();
        return true;
    }

    public function getQuestion($teachChapterId, $questionType)
    {
        $info = self::where('id', $teachChapterId)->find();
        if (empty($info)) {
            throw new ValidateException('章节不存在');
        }
        $knowledgeIds = '';
        if ($questionType == 1) {
            $knowledgeIds = $info->beforeClassQuestion;
        } else if ($questionType == 2) {
            $knowledgeIds = $info->inClassQuestion;
        } else {
            $knowledgeIds = $info->afterClassQuestion;
        }
        $list = SubjectQuestion::with([
            'knowledge' => function ($query) {
                $query->field('id,name');
            }])->where([
            ['id', 'in', $knowledgeIds],
            ['status', '=', SubjectKnowledgeStatusEnum::E1]
        ])->field('id,subjectKnowledgeId,name')->select();
        foreach ($list as $item) {
            if (!empty($item['knowledge'])) {
                if (!empty($item['knowledge']['pid'])) {
                    $pid = $item['knowledge']['pid'];
                    $pidKnowledge = SubjectKnowledgeModel::where(['id' => $pid, 'status' => SubjectKnowledgeStatusEnum::E1])->field('id,name')->find();
                    unset($item['knowledge']['pid']);
                    $pidKnowledge['children'] = $item['knowledge'];
                    $item['knowledge'] = $pidKnowledge;
                } else {
                    $item['knowledge']['children'] = null;
                    unset($item['knowledge']['pid']);
                }
            }
        }
        return $list;
    }



    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------
    public function gradeInfo()
    {
        return $this->hasOne(SubjectGrade::class, 'id', 'subjectGradeId');
    }

    public function subject()
    {
        return $this->hasOne(Subject::class, 'id', 'subjectId');
    }

    public function knowledge()
    {
        return $this->hasOne(SubjectKnowledge::class, 'id', 'subjectKnowledgeId');
    }

}